#include "UdpClient.hpp"
#include "Common.hpp"
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// Client
// ./client_upd serverip serverport -- 客户端知晓要连接服务器的ip和对应进程的port，即可访问服务器对应的进程
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage : " << argv[0] << "serverip serverport" << std::endl;
        Die(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建socket
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0); //协议族-IPv4 or IPv6; 通信类型-TCP or UDP；指定协议-可以设置为0作为默认
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(SOCKET_ERR);
    }

    // 1.1 填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server)); // TODO..
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    // 2.clientdone
    while (true)
    {
        std::cout << "Please Enter# ";
        std::string message;
        std::getline(std::cin, message);
        
        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        (void)n;

        //temp作为输出型参数的实参，存放接收信息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        //socket对象对应的fd，存放接收数据的缓冲区，该缓冲区大小(认为收到的为字符串)，flag可设置为0，发送方的sockaddr，该sockaddr的结构体大小
        n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n > 0)
        {   //认为收到的信息为字符串格式
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}
